dofile ("libColor.lua")
dofile ("StylusBox.lua")
dofile ("libKeyboard.lua")

TextBox = {}

tbx = 0
tby = 0

function TextBox.init (txb, x, y, larg, haut) --, mode)
  local tb = tostring (txb)
  
  _G[tb] = {}
  
  _G[tb].x = x
  _G[tb].y = y
  
  _G[tb].larg = larg
  _G[tb].haut = haut
  
  _G[tb].x2 = _G[tb].x+_G[tb].larg
  _G[tb].y2 = _G[tb].y+_G[tb].haut
  
  _G[tb].mode = 1 --mode
  
  _G[tb].box = newBox (_G[tb].x, _G[tb].y, _G[tb].x2, _G[tb].y2)
  
  _G[tb].hasfocus = false
  
  _G[tb].k = tb..".keyboard"
  
  Keyboard.init (_G[tb].k, 18, 9*8)
  
  _G[tb].txtbybx = math.ceil(_G[tb].x/6)
end

function TextBox.draw (txb)
  local tb = tostring (txb)
  
  if Stylus.held then
    tbx = Stylus.X
    tby = Stylus.Y
    _G[tb].hasfocus = false
  end
  
  Keyboard.draw (_G[tb].k)
  
  if _G[tb].mode == 1 then
    Button.disable (_G[_G[tb].k].bts[55])
  elseif _G[tb].mode == 2 then
    Button.enable (_G[_G[tb].k].bts[55])
  end
  
  screen.drawFillRect (SCREEN_DOWN, _G[tb].x, _G[tb].y, _G[tb].x2, _G[tb].y2, c_blanc)
  screen.drawRect (SCREEN_DOWN, _G[tb].x+1, _G[tb].y+1, _G[tb].x2, _G[tb].y2, c_gris)
  screen.drawRect (SCREEN_DOWN, _G[tb].x, _G[tb].y, _G[tb].x2, _G[tb].y2, c_blanc)
  
  local txt = Keyboard.text (_G[tb].k)
  
  if _G[tb].hasfocus then
    screen.print (SCREEN_DOWN, _G[tb].x+3, _G[tb].y+3, txt.."|", c_noir)
  else 
    screen.print (SCREEN_DOWN, _G[tb].x+3, _G[tb].y+3, txt, c_noir)
  end
  
  if Stylus.heldinBox (_G[tb].box, tbx, tby) then
    _G[tb].hasfocus = true
  end
  
  if Keyboard.isAnyKeyPressed (_G[tb].k) then
    _G[tb].hasfocus = true
  end
  
  _G[_G[tb].k].visible = _G[tb].hasfocus
end

function TextBox.text (txb)
  local tb = tostring (txb)
  
  return string.sub(Keyboard.text (_G[tb].k), 1, _G[tb].txtbybx)
end

function TextBox.clear (txb)
  local tb = tostring (txb)
  
  _G[tb] = nil
  
  tbx = nil
  tby = nil
  
  Keyboard.clear (_G[tb].k)
end

